package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IMemberService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import io.swagger.annotations.Example;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName MemberController
 * @Description 会员中心控制层
 * @Author ciggar
 * @Date 2019-08-07 14:26
 * @Version 1.0
 **/
@RestController
@RequestMapping("/user")
public class MemberController {

    @Reference(timeout = 3000,check = false)
    IMemberService memberService;

    @Reference(timeout = 3000,check = false)
    IKaptchaService kaptchaService;

    /**
     * 根据ID查询单条会员信息
     * @param id 编号
     * @return
     */
    @GetMapping("/member/{id}")
    public ResponseData searchMemberById(@PathVariable(name = "id")long id) {
        QueryMemberRequest request=new QueryMemberRequest();
        request.setUserId(id);
        QueryMemberResponse queryMemberResponse = memberService.queryMemberById(request);
        if (!queryMemberResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(queryMemberResponse.getMsg());
        }
        return new ResponseUtil<>().setData(queryMemberResponse);
    }

    /**
     * 会员信息更新
     * @return
     */
    @PutMapping("/member")
    public ResponseData updateUser(@RequestBody UpdateMemberRequest request) {
        UpdateMemberResponse response = memberService.updateMember(request);
        if(response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     *会员登录，验证用户信息，验证码，存放用户信息token到cookie里
     * @return
     */
    @Anoymous
    @PostMapping("login")
    public ResponseData login(@RequestBody UserLoginRequest user, HttpServletRequest request, HttpServletResponse response) {
        String code = user.getCaptcha();
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(code);
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(kaptchaCodeResponse.getCode())) return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        UserLoginResponse userLoginResponse = memberService.verifyLogin(user);
        if (!SysRetCodeConstants.SUCCESS.getCode().equals(userLoginResponse.getCode())) return new ResponseUtil<>().setErrorMsg(userLoginResponse.getMsg());

        Cookie cookie=CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN,userLoginResponse.getToken(),"/",24*60*60);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);

        return new ResponseUtil<>().setData(userLoginResponse);
    }

    /**
     *登录验证
     * @return
     */
    @GetMapping("login")
    public ResponseData login(HttpServletRequest request) {
        String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        Map map = memberService.verify(userInfo);
        return new ResponseUtil<>().setData(map);
    }

    /**
     *退出登录，删除cookie
     * @return
     */
    @GetMapping("loginOut")
    public ResponseData loginOut(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals(TokenIntercepter.ACCESS_TOKEN)) {
                    c.setValue(null);
                    c.setMaxAge(0);
                    c.setPath("/");
                    response.addCookie(c);
                }
            }
        }
        return new ResponseUtil<>().setData(null);
    }

}

